<template>
  <div class="modal-overlay" ref="modalRef">
    <div class="modal-content max-w-6xl w-full max-h-[90vh]">
      <!-- 标题栏 -->
      <div class="bg-gray-100 px-6 py-3 border-b border-gray-200 flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <div class="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center">
            <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
            </svg>
          </div>
          <h3 class="text-lg font-semibold text-gray-900">图片预览</h3>
        </div>
        <button 
          @click="$emit('close')"
          class="text-gray-500 hover:text-gray-700 transition-colors"
        >
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
          </svg>
        </button>
      </div>

      <!-- 文件信息栏 -->
      <div class="bg-gray-50 px-6 py-3 border-b border-gray-200 flex items-center space-x-4">
        <input 
          type="checkbox" 
          :checked="file.selected"
          @change="$emit('toggle-select', file)"
          class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
        />
        <span class="font-medium text-gray-900">{{ file.name }}</span>
        <span class="text-gray-500 text-sm">{{ file.path }}</span>
      </div>

      <!-- 主内容区域 -->
      <div class="flex h-[calc(90vh-200px)]">
        <!-- 左侧图片预览 -->
        <div class="flex-1 p-6 flex items-center justify-center bg-gray-100">
          <div class="relative max-w-full max-h-full">
            <img 
              :src="imageUrl" 
              :alt="file.name"
              class="max-w-full max-h-full object-contain rounded-lg shadow-lg"
              @load="onImageLoad"
              @error="onImageError"
            />
            <div v-if="loading" class="absolute inset-0 flex items-center justify-center bg-white bg-opacity-75 rounded-lg">
              <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
            </div>
            <div v-if="error" class="absolute inset-0 flex items-center justify-center bg-red-50 rounded-lg">
              <div class="text-center">
                <svg class="w-16 h-16 text-red-400 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
                </svg>
                <p class="text-red-600 font-medium">图片加载失败</p>
                <p class="text-red-500 text-sm">{{ error }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧信息面板 -->
        <div class="w-80 bg-white border-l border-gray-200 p-6 overflow-y-auto">
          <!-- 组别导航 -->
          <div class="mb-6">
            <h4 class="text-sm font-medium text-gray-700 mb-3">重复组导航</h4>
            <div class="flex items-center justify-between bg-gray-50 rounded-lg p-3">
              <button 
                @click="previousGroup"
                :disabled="currentGroupIndex === 0"
                class="p-2 rounded-lg hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
              </button>
              <span class="font-medium text-gray-900">组别 {{ currentGroupIndex + 1 }}</span>
              <button 
                @click="nextGroup"
                :disabled="currentGroupIndex === duplicateGroup.files.length - 1"
                class="p-2 rounded-lg hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
              </button>
            </div>
          </div>

          <!-- 缩略图列表 -->
          <div class="mb-6">
            <h4 class="text-sm font-medium text-gray-700 mb-3">组内文件</h4>
            <div class="space-y-3">
              <div 
                v-for="(groupFile, index) in duplicateGroup.files" 
                :key="index"
                class="border border-gray-200 rounded-lg p-3 hover:bg-gray-50 transition-colors cursor-pointer"
                :class="{ 'ring-2 ring-blue-500 bg-blue-50': index === currentGroupIndex }"
                @click="selectFile(index)"
              >
                <div class="flex items-start space-x-3">
                  <input 
                    type="checkbox" 
                    :checked="groupFile.selected"
                    @change="$emit('toggle-select', groupFile)"
                    class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500 mt-1"
                  />
                  <div class="flex-1 min-w-0">
                    <div class="text-sm font-medium text-gray-900 truncate">{{ groupFile.name }}</div>
                    <div class="text-xs text-gray-500 space-x-2">
                      <span>{{ formatFileSize(groupFile.size) }}</span>
                      <span>{{ getImageResolution(groupFile) }}</span>
                      <span>{{ getFileExtension(groupFile.name) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 显示选项 -->
          <div class="mb-6">
            <h4 class="text-sm font-medium text-gray-700 mb-3">显示选项</h4>
            <div class="space-y-3">
              <label class="flex items-center">
                <input 
                  type="checkbox" 
                  v-model="displayOptions.adaptScaling"
                  class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                />
                <span class="ml-2 text-sm text-gray-700">适配图像缩放</span>
              </label>
              <label class="flex items-center">
                <input 
                  type="checkbox" 
                  v-model="displayOptions.correctOrientation"
                  class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                />
                <span class="ml-2 text-sm text-gray-700">修正朝向</span>
              </label>
              <label class="flex items-center">
                <input 
                  type="checkbox" 
                  v-model="displayOptions.showLabels"
                  class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                />
                <span class="ml-2 text-sm text-gray-700">显示标签</span>
              </label>
              <label class="flex items-center">
                <input 
                  type="checkbox" 
                  v-model="displayOptions.showThumbnails"
                  class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                />
                <span class="ml-2 text-sm text-gray-700">显示缩略图</span>
                <svg class="w-4 h-4 ml-1 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
              </label>
            </div>
          </div>

          <!-- 缩放控制 -->
          <div>
            <h4 class="text-sm font-medium text-gray-700 mb-3">缩放控制</h4>
            <div class="flex items-center space-x-3">
              <svg class="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"></path>
              </svg>
              <input 
                type="range" 
                v-model="zoomLevel" 
                min="0.1" 
                max="3" 
                step="0.1"
                class="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer slider"
              />
              <span class="text-sm font-medium text-gray-700 min-w-[3rem]">{{ Math.round(zoomLevel * 100) }}%</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="bg-gray-50 px-6 py-3 border-t border-gray-200 flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <button 
            @click="deleteSelected"
            class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
          >
            删除选中文件
          </button>
          <button 
            @click="moveToTrash"
            class="px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition-colors"
          >
            移动到回收站
          </button>
        </div>
        <div class="flex items-center space-x-3">
          <span class="text-sm text-gray-600">
            已选择 {{ selectedCount }} 个文件
          </span>
          <button 
            @click="$emit('close')"
            class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { convertFileSrc } from '@tauri-apps/api/tauri'

interface FileInfo {
  name: string
  path: string
  size: number
  modified: Date
  selected: boolean
}

interface DuplicateGroup {
  files: FileInfo[]
  size: number
}

interface Props {
  file: FileInfo
  duplicateGroup: DuplicateGroup
  currentGroupIndex: number
}

const props = defineProps<Props>()

// 显示选项
const displayOptions = ref({
  adaptScaling: true,
  correctOrientation: true,
  showLabels: false,
  showThumbnails: true
})

// 缩放控制
const zoomLevel = ref(1)

// 图片加载状态
const loading = ref(true)
const error = ref('')

// 计算属性
const imageUrl = computed(() => {
  // 使用 Tauri 的 convertFileSrc 来正确处理文件路径
  try {
    return convertFileSrc(props.file.path)
  } catch (error) {
    console.error('转换文件路径失败:', error)
    // 如果转换失败，尝试使用原始路径
    return `file://${props.file.path}`
  }
})

const selectedCount = computed(() => {
  return props.duplicateGroup.files.filter(f => f.selected).length
})

// 方法
const onImageLoad = () => {
  loading.value = false
  error.value = ''
}

const onImageError = () => {
  loading.value = false
  error.value = '无法加载图片文件'
}

const selectFile = (index: number) => {
  emit('select-file', index)
}

const previousGroup = () => {
  if (props.currentGroupIndex > 0) {
    emit('select-file', props.currentGroupIndex - 1)
  }
}

const nextGroup = () => {
  if (props.currentGroupIndex < props.duplicateGroup.files.length - 1) {
    emit('select-file', props.currentGroupIndex + 1)
  }
}

const deleteSelected = () => {
  emit('delete-selected')
}

const moveToTrash = () => {
  emit('move-to-trash')
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getImageResolution = (file: FileInfo) => {
  // 这里应该从图片元数据中获取分辨率
  // 暂时返回占位符
  return '2736x3648'
}

const getFileExtension = (filename: string) => {
  return filename.split('.').pop()?.toUpperCase() || 'UNKNOWN'
}

// 暴露方法给父组件
defineExpose({
  displayOptions,
  zoomLevel
})

// 定义事件
const emit = defineEmits<{
  close: []
  'toggle-select': [file: FileInfo]
  'select-file': [index: number]
  'delete-selected': []
  'move-to-trash': []
}>()

// 弹窗定位管理
const modalRef = ref<HTMLElement | null>(null)

// 动态定位弹窗
const positionModal = () => {
  if (modalRef.value) {
    const modal = modalRef.value
    // 强制设置弹窗位置
    modal.style.position = 'fixed'
    modal.style.top = '0px'
    modal.style.left = '0px'
    modal.style.width = '100vw'
    modal.style.height = '100vh'
    modal.style.zIndex = '9999'
    
    // 确保弹窗内容居中
    const content = modal.querySelector('.modal-content') as HTMLElement
    if (content) {
      content.style.position = 'absolute'
      content.style.top = '50%'
      content.style.left = '50%'
      content.style.transform = 'translate(-50%, -50%)'
    }
  }
}

// 监听窗口变化
const handleResize = () => {
  positionModal()
}

// 组件挂载后设置弹窗定位
onMounted(() => {
  window.addEventListener('resize', handleResize)
  // 初始定位弹窗
  nextTick(() => {
    positionModal()
  })
})

// 组件卸载后清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.slider::-webkit-slider-thumb {
  appearance: none;
  height: 20px;
  width: 20px;
  border-radius: 50%;
  background: #3b82f6;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.slider::-moz-range-thumb {
  height: 20px;
  width: 20px;
  border-radius: 50%;
  background: #3b82f6;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
</style>
